package com.koron.css2.baseConfig.impl;

import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.DeleteFileUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Bookmark;
import org.apache.poi.hwpf.usermodel.Bookmarks;
import org.apache.poi.hwpf.usermodel.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ContractTemplateAction {
	private Logger log = LogManager.getLogger(ContractTemplateAction.class);
	
	@Autowired
	private ContractTemplateService contractTemplateService;
	
	@RequestMapping(value="/contractTemplatePrint.api",method = RequestMethod.POST)
	public String print(@RequestBody RequestBean req,
			HttpServletRequest request,HttpServletResponse response) 
			throws Exception {
		InputStream is = null;
		InputStream inputStream = null;
		try {

			//入参转换
			Map map = JsonUtils.objectToPojo(req.getData(), Map.class);
			//MessageBean<String> msg = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", String.class);
			//String parentDir = request.getServletContext().getRealPath("static\\addone\\upload");
			//String templatePath = "../../upload/"+map.get("fjName");  
		     is = getFileStream(map.get("fjName").toString()); 
		     if(is==null) 
		    	 return null;
			//判断是否打印
			if (map != null ) {
//				 HashMap m = ADOConnection.runTask("_default", contractTemplateService, "getPrintData",
//							HashMap.class,map.get("userNo").toString());
				
				 HashMap m = new HashMap();
				 m.put("zb_hm", map.get("userNo").toString());
			     HWPFDocument document = new HWPFDocument(is);  
			     Bookmarks bookmarks = document.getBookmarks();
			        for(int dwI = 0;dwI < bookmarks.getBookmarksCount();dwI++){
			            Bookmark bookmark = bookmarks.getBookmark(dwI);
			            if(m.containsKey(bookmark.getName())){
			                Range range = new Range(bookmark.getStart(),bookmark.getEnd(),document);
			                range.replaceText(m.get(bookmark.getName()).toString(),false);
			            }
			        }
		          response.setContentType("application/msword;charset=UTF-8");
 	              response.setCharacterEncoding("UTF-8");
 	              // response.setContentType("application/force-download");
 	              response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode("合同","UTF-8"));
//			      String filename = UUID.randomUUID().toString();
//			      OutputStream out = new  FileOutputStream("../../upload/"+filename+".doc");
//			      String filename = UUID.randomUUID().toString();
//			      OutputStream out = new FileOutputStream("../../upload/"+filename+".pdf");
//			      PdfOptions options = PdfOptions.create();
//			      PdfConverter.getInstance().convert(document, out, options);
 	              OutputStream os = response.getOutputStream();
			      //把doc输出到输出流中  
			      document.write(os); 
//			      File file = new File("../../upload/"+filename+".doc");
//			      inputStream = new FileInputStream(file);
//			      byte[] buffer = new byte[1024];
//		            BufferedInputStream bis = null;
//		            OutputStream os = null; //输出流
//		            try {
//		                os = response.getOutputStream();
//		                bis = new BufferedInputStream(inputStream);
//		                int i = bis.read(buffer);
//		                while(i != -1){
//		                    os.write(buffer);
//		                    i = bis.read(buffer);
//		                }
//		                
//
//		            } catch (Exception e) {
//		            	log.error("文件读写错误");
//		            	
//		            }
//		            try {
//		                bis.close();
//		                inputStream.close();
//		            } catch (IOException e) {
//		                // TODO Auto-generated catch block
//		               log.error("关闭流错误");
//		            }
			} 
			return null;
		} catch (Exception e) {
			log.error("查询用户失败", e);
			return null;
		}finally {
			if(is != null)
				is.close();
		}
	}
	
	/**
	 * 获取文件流
	 * 
	 * @param url
	 * @return
	 */
	private InputStream getFileStream(String url) {
		try {
			HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setReadTimeout(5000);
			connection.setConnectTimeout(5000);
			connection.setRequestMethod("GET");
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream inputStream = connection.getInputStream();
				return inputStream;
			}
		} catch (IOException e) {
			log.error("获取文件路径为：" + url);
	
		}
		return null;
	}
	@RequestMapping(value="/contractTemplateUpload.api",method = RequestMethod.POST)
	public MessageBean<?> upload(@RequestParam(required = true, name = "file") MultipartFile file,
			@RequestParam(required = true, name = "type") String type,
			@RequestParam(required = true, name = "fjName") String fjName,
			HttpServletRequest request) 
			throws Exception {
		
		
		// 判断上传的文件是否为空
		boolean isEmpty = file.isEmpty();
		if (isEmpty) {
			log.error("上传失败,上传的文件为空");
			return MessageBean.create(Constant.MESSAGE_INT_FAIL, "上传失败,上传的文件为空", void.class);
		}
		
		// 检查文件大小
		long fileSize = file.getSize();
		if (fileSize > 3 * 1024 * 1024) {
			log.error("上传失败！上传的文件大小超出了限制");
			return MessageBean.create(Constant.MESSAGE_INT_FAIL, "上传失败！上传的文件大小超出了限制", void.class);
		}
		
		// 检查文件MIME类型
		String contentType = file.getContentType();
		List<String> types = new ArrayList<String>();
		types.add("application/msword");
		if (!types.contains(contentType)) {
			log.error("上传失败！不允许上传此类型的文件！");
			return MessageBean.create(Constant.MESSAGE_INT_FAIL, "上传失败！不允许上传此类型的文件！", void.class);
		}
		
		// 准备文件夹,获取项目中upload文件夹的路径
		//String parentDir = request.getServletContext().getRealPath("upload");

		if("ContractTemplateUpdate".equals(type)) {
			DeleteFileUtil.delete("../../upload/"+fjName);
		}
		
		
		// request.getSession().getServletContext().getRealPath("");
		// request.getRealPath("");
		File parent = new File("../../upload/");
		if (!parent.exists()) {
			parent.mkdirs();
		}
		
		// 获取原始文件名
		String originalFilename = file.getOriginalFilename();
		
//		// 确定最终保存时使用的文件
//		String filename = UUID.randomUUID().toString();
//		String suffix = "";
//		int beginIndex = originalFilename.lastIndexOf(".");
//		if (beginIndex != -1) {
//			suffix = originalFilename.substring(beginIndex);
//		}
		
		// 执行保存文件
		File dest = new File(parent, originalFilename);
		file.transferTo(dest);
		
		return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", void.class);

	}
}
